package xps.and.uudaijia.userclient.view.activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jude.utils.JUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import xps.and.uudaijia.userclient.Constants;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.WXParmas;
import xps.and.uudaijia.userclient.data.baen.AliPayResult;
import xps.and.uudaijia.userclient.data.baen.AliPrePayOrder;
import xps.and.uudaijia.userclient.data.baen.CodeBean;
import xps.and.uudaijia.userclient.data.baen.CostBean;
import xps.and.uudaijia.userclient.data.baen.PrePayOrder;
import xps.and.uudaijia.userclient.data.baen.WXPayResult;
import xps.and.uudaijia.userclient.data.net.PayNetWork;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.util.APay_v2;
import xps.and.uudaijia.userclient.view.base.BaseActivity;

/**
 * Created by XPS on 2017/6/24.
 */

public class DaiJiaPayMentActivity extends BaseActivity {
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    @BindView(R.id.actionbar_tv_right)
    TextView actionbarTvRight;
    @BindView(R.id.v_gap_line)
    View vGapLine;
    @BindView(R.id.actionbar_al)
    AutoRelativeLayout actionbarAl;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.start_Text)
    TextView startText;
    @BindView(R.id.mileage_Text)
    TextView mileageText;
    @BindView(R.id.wait_Text)
    TextView waitText;
    @BindView(R.id.ar_alipay)
    AutoRelativeLayout arAlipay;
    @BindView(R.id.ar_wxpay)
    AutoRelativeLayout arWxpay;
    @BindView(R.id.ar_balance)
    AutoRelativeLayout arBalance;
    @BindView(R.id.Remarks_Text)
    TextView RemarksText;
    @BindView(R.id.bt_dopay)
    Button btDopay;
    @BindView(R.id.additional_Text)
    TextView additionalText;
    @BindView(R.id.WX_Layout)
    AutoFrameLayout WXLayout;
    @BindView(R.id.ZFB_Layout)
    AutoFrameLayout ZFBLayout;
    @BindView(R.id.YE_Layout)
    AutoFrameLayout YELayout;
    @BindView(R.id.XJ_Text)
    TextView XJText;
    private IWXAPI api;
    String OrderId;
    PrePayOrder.ReturnBodyBean responseBody;
    String zfbID;
    String driverName;
    String driverHeadImg;
    @Override
    protected int getLayout() {
        return R.layout.activity_daijaipayment;
    }

    @Override
    protected void setData() {

    }

    /*
    * 只在微信支付成功的时候回调
    * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(WXPayResult a) {
        dissmisDialog();
        if (a.getErrCode() == 0) {
            Intent i = new Intent(this, CommentDriverActivity.class);
            i.putExtra("orderId", OrderId);
            i.putExtra("driverName", driverName);
            i.putExtra("driverHeadImg", driverHeadImg);
            startActivity(i);
            finish();
        }
    }

    /*
      * 只在支付宝支付成功的时候回调
      * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AliPayResult aliPayResult) {
        //没有处理内容 收到回调就代表成功
        dissmisDialog();
        if (aliPayResult.isSuccess()) {
            Intent i = new Intent(this, CommentDriverActivity.class);
            i.putExtra("orderId", OrderId);
            i.putExtra("driverName", driverName);
            i.putExtra("driverHeadImg", driverHeadImg);
            startActivity(i);
            finish();
        }

    }

    @Override
    protected void init() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        Intent intent = getIntent();
        OrderId = intent.getStringExtra("orderID");
        driverName = intent.getStringExtra("driverName");
        driverHeadImg = intent.getStringExtra("driverHeadImg");
        actionbarTvTitle.setText("支付订单");
        reset();
        paymentCost();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    void reset() {
        arAlipay.setBackgroundResource(R.drawable.item_uncheck_bk);
        arBalance.setBackgroundResource(R.drawable.item_uncheck_bk);
        arWxpay.setBackgroundResource(R.drawable.item_uncheck_bk);
    }

    @OnClick({R.id.actionbar_iv_back, R.id.WX_Layout, R.id.ZFB_Layout, R.id.YE_Layout, R.id.XJ_Text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                DaiJiaPayMentActivity.this.finish();
                break;
            case R.id.WX_Layout:
                WXCont();
                break;
            case R.id.ZFB_Layout:
                ZFBCont();
                break;
            case R.id.YE_Layout:
                YECont();
                break;
            case R.id.XJ_Text:
                XJCont();
                break;
        }
    }

    void WXCont() {
        PayNetWork.perPay(OrderId, new Subscriber<PrePayOrder>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(PrePayOrder prePayOrder) {
                Log.e("PaymentActivity", prePayOrder.toString());
                responseBody = prePayOrder.getReturn_body();
                String prePayId = responseBody.getPrepayid();
                doPay(new WXParmas(prePayId));
            }
        });
    }


    void ZFBCont() {
        PayNetWork.ZFBCont(OrderId, new Subscriber<AliPrePayOrder>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(AliPrePayOrder aliPrePayOrder) {
                if (aliPrePayOrder.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(aliPrePayOrder.getReturn_msg());
                } else if (aliPrePayOrder.getReturn_code().equals("SUCCESS")) {
                    zfbID = aliPrePayOrder.getReturn_body().getOrderString();
                    APay_v2.getInstance().setContext(DaiJiaPayMentActivity.this).doPay_v2(zfbID);
                }
            }
        });
    }

    void YECont() {
        PayNetWork.YECont(OrderId, new Subscriber<CodeBean>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(CodeBean codeBean) {
                if (codeBean.getReturn_code().equals("SUCCESS")) {
                    Intent i = new Intent(DaiJiaPayMentActivity.this, CommentDriverActivity.class);
                    i.putExtra("orderId", OrderId);
                    i.putExtra("driverName", driverName);
                    i.putExtra("driverHeadImg", driverHeadImg);
                    startActivity(i);
                    finish();
                } else if (codeBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(codeBean.getReturn_msg());
                }
            }
        });
    }

    void XJCont() {
        PayNetWork.XJCont(OrderId, new Subscriber<CodeBean>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(CodeBean codeBean) {
                if (codeBean.getReturn_code().equals("SUCCESS")) {
                    Intent i = new Intent(DaiJiaPayMentActivity.this, CommentDriverActivity.class);
                    i.putExtra("orderId", OrderId);
                    i.putExtra("driverName", driverName);
                    i.putExtra("driverHeadImg", driverHeadImg);
                    startActivity(i);
                    finish();
                } else if (codeBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(codeBean.getReturn_msg());
                }
            }
        });
    }

    void doPay(WXParmas wx) {
        showDialogNoCancel();
        PayReq payReq = new PayReq();
        payReq.appId = wx.appid;
        payReq.partnerId = wx.partnerid;
        payReq.prepayId = wx.prepayid;
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = wx.noncestr;
        payReq.timeStamp = wx.timestamp;
        payReq.sign = wx.sign;
        api.sendReq(payReq);
    }

    void paymentCost() {
        UserNetWorks.getPaymentCost(OrderId, new Subscriber<CostBean>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialogNoCancel();
            }

            @Override
            public void onCompleted() {
                dissmisDialog();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(CostBean costBean) {
                CostBean.ReturnBodyBean returnBodyBean = costBean.getReturn_body();
                if (costBean.getReturn_code().equals("SUCCESS")) {
                    tvPrice.setText("" + returnBodyBean.getTotalMoney());
                    startText.setText("起步价:" + returnBodyBean.getStartingPrice() + "元");
                    mileageText.setText("里程费:" + returnBodyBean.getMileageFee() + "元");
                    waitText.setText("等待费:" + returnBodyBean.getWaitMoney() + "元");
                    RemarksText.setText("费用备注:" + returnBodyBean.getAddRemark() + "元");
                    btDopay.setText("实付价格:" + returnBodyBean.getRealTotalMoney() + "元");
                    additionalText.setText("附加费用:" + returnBodyBean.getAddMoney() + "元");
                } else if (costBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(costBean.getReturn_msg());
                }

            }
        });

    }
}
